package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.pojo.OrderSetting;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("ordersetting")
@Slf4j
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile multipartFile){
        log.info("[预约设置-上传]fileName:{},size；{}",multipartFile.getOriginalFilename(),multipartFile.getSize());
        String originalFilename = multipartFile.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)){
            return new Result(false,"缺少文件名");
        }
        //1.抽取excel数据poi
        try (InputStream is=multipartFile.getInputStream()){
            Workbook workbook=null;
            //1.1构造工作簿
            if (originalFilename.endsWith(".xls")){
                //excel2003
                workbook=new HSSFWorkbook(is);
            }else if (originalFilename.endsWith(".xlsx")){
                //excel2007
                workbook=new XSSFWorkbook(is);
            }else{
                return new Result(false,"文件格式不正确，请重新尝试！");
            }
            List<OrderSetting> orderSettings=new ArrayList<>();
            //1.2遍历sheet
            for (Sheet sheet : workbook) {
                //1.3遍历行
                for (int i = 1; i <=sheet.getLastRowNum() ; i++) {
                    //1.4抽取单元格数据
                    Row row =sheet.getRow(i);
                    Date date=null;
                    Integer number=null;
                    try {
                        date=null !=row.getCell(0)?row.getCell(0).getDateCellValue():null;
                        number=null !=row.getCell(1)?Double.valueOf(row.getCell(1).getNumericCellValue()).intValue():null;
                    } catch (IllegalStateException|NumberFormatException e) {
                        log.info("",e);
                        return new Result(false,String.format("数据格式不正确, %s " +
                                "第%d行",sheet.getSheetName(),row.getRowNum()+1));
                    }

                    if (date==null || number == null){
                        return new Result(false,String.format("缺少数据, %s 第%d行",sheet.getSheetName(),row.getRowNum()+1));
                    }
                    //1.5构造orderSetting
                    orderSettings.add(new OrderSetting(date,number));
                }
            }
            log.info("[预约设置-批量导入]解析完成，data:{}",orderSettings);

            //2-数据提交到数据库
            orderSettingService.addAll(orderSettings);
            return new Result(true, MessageConst.IMPORT_ORDERSETTING_SUCCESS);

        } catch (RuntimeException|IOException e) {
            log.error("",e);
            return new Result(false, MessageConst.IMPORT_ORDERSETTING_FAIL);
        }
    }
    @GetMapping("/findByMonth")
    public Result findByMonth(Integer month,Integer year){
        //RPC查询数据
        List<OrderSetting> orderSettings=orderSettingService.findByMonth(month,year);

        List<Map<String,Object>> resultList=orderSettings.stream().map(e->{
            Map<String, Object> map = new HashMap<>();
            //     { date: 3, number: 100, reservations: 0 },
            Calendar cal=Calendar.getInstance();
            cal.setTime(e.getOrderDate());
            map.put("date",cal.get(Calendar.DAY_OF_MONTH));
            map.put("number",e.getNumber());
            map.put("reservations",e.getReservations());
            return map;
        }).collect(Collectors.toList());

        return new Result(true,MessageConst.GET_ORDERSETTING_SUCCESS,resultList);
    }

    @RequestMapping("editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        log.info("[预约设置-根据日期编辑]data:{}",orderSetting);
        try {
            orderSettingService.editNumberByDate(orderSetting.getOrderDate(),orderSetting.getNumber());
            return new Result(true,MessageConst.ORDERSETTING_SUCCESS);
        } catch (RuntimeException e) {
            log.error("",e);
            return new Result(false,MessageConst.ORDERSETTING_FAIL);
        }
    }



    public static void main(String[] args) throws IOException {
    //读操作
        //        XSSFWorkbook workbook = new XSSFWorkbook
        // ("E:\\jiuyeban\\kejian\\传智健康\\005\\传智健康_第5天\\03-其他资料\\ordersetting_demo.xlsx");
//        for (Sheet sheet : workbook) {
//            System.out.println("..........." + sheet);
//
//            for (Row row : sheet) {
//                for (Cell cell : row) {
//                        System.out.print(cell.getStringCellValue());
//                    }
//                    System.out.println("");
//                }
//            }
//            workbook.close();

        //写
        XSSFWorkbook workbook=new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("传智播客");
        //创建第一行
        XSSFRow row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("编号");
        row1.createCell(1).setCellValue("名称");
        row1.createCell(2).setCellValue("年龄");

        XSSFRow row2 = sheet.createRow(1);
        row2.createCell(0).setCellValue("1");
        row2.createCell(1).setCellValue("名称1");
        row2.createCell(2).setCellValue("年龄1");
        XSSFRow row3 = sheet.createRow(2);
        row3.createCell(0).setCellValue("2");
        row3.createCell(1).setCellValue("名称2");
        row3.createCell(2).setCellValue("年龄2");

        OutputStream os=new FileOutputStream("E:\\\\jiuyeban\\\\kejian\\\\传智健康\\\\005\\\\传智健康_第5天\\\\03-其他资料\\\\ordersetting_demo.xlsx");
        workbook.write(os);
        os.close();
        workbook.close();
    }


}